package com.zzyang.mybatis.jdbc.spring.config;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;

import static com.zzyang.mybatis.jdbc.spring.config.SeparationJdbcProperties.PREFIX;

/**
 * 数据源配置
 *
 * @author zhuoziyang
 * @date 2021/4/8 20:56
 */
@ConfigurationProperties(prefix = PREFIX)
public class SeparationJdbcProperties implements InitializingBean {

    public static final String PREFIX = "spring.mybatis.jdbc";

    /**
     * 主数据源id
     */
    private String masterDataSourceId;

    private List<DataSourceDefinition> datasources;

    private String loadbalance;

    private String cluster;

    public String getCluster() {
        return cluster;
    }

    public void setCluster(String cluster) {
        this.cluster = cluster;
    }

    public String getMasterDataSourceId() {
        return masterDataSourceId;
    }

    public void setMasterDataSourceId(String masterDataSourceId) {
        this.masterDataSourceId = masterDataSourceId;
    }

    public String getLoadbalance() {
        return loadbalance;
    }

    public void setLoadbalance(String loadbalance) {
        this.loadbalance = loadbalance;
    }

    public List<DataSourceDefinition> getDatasources() {
        return datasources;
    }

    public void setDatasources(List<DataSourceDefinition> datasources) {
        if (CollectionUtils.isEmpty(datasources)){
            return;
        }
        for (DataSourceDefinition datasource : datasources) {
            if (!StringUtils.hasText(datasource.getId())){
                throw new IllegalArgumentException("数据源id不能为空");
            }
        }
        this.datasources = datasources;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        if (!StringUtils.hasText(masterDataSourceId)) {
            throw new IllegalArgumentException("masterDataSourceId 不能为空");
        }
    }

}
